package com.igeek.compus.backend.sysuser.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.igeek.compus.backend.system.Constants;
import com.igeek.compus.backend.system.R;
import com.igeek.compus.backend.sysuser.entity.SysUser;
import com.igeek.compus.backend.sysuser.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Slf4j
@Controller
@RequestMapping("sysUser")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("login.do")
    @ResponseBody
    public R login(SysUser sysUser, HttpSession session) {

        if (StrUtil.isEmpty(sysUser.getUsername()) || StrUtil.isEmpty(sysUser.getPassword())) {
            return R.fail("账号密码不能为空");
        }

        //  加密入库
        sysUser.setPassword(SecureUtil.md5(sysUser.getPassword()));

        try {
            SysUser sysUserInDB = sysUserService.checkSysUser(sysUser);
            if (ObjectUtil.isNotNull(sysUserInDB)) {
                session.setAttribute(Constants.SYS_USER, sysUserInDB);
                return R.success();
            } else {
                return R.fail("账号密码错误");
            }
        } catch (Exception e) {
            log.error("sysUser login异常：" + e);
            return R.fail("系统错误");
        }
    }


}
